<?php
class CatalogController extends Core_Controller_BaseController
{
	private $tableCatalog = null;

	public function init()
	{
		parent::init();
	}

    public function addAction()
    {
		$initialVals= array();
		$parentId = $this->_getParam('p');
		if ( is_null( $parentId ) ){
			throw new Exception('No parent node');
		}
		$initialVals['parent_id'] = $parentId;
		
		$addForm = new Application_Form_Catalog_Add( $initialVals );

		if ( $this->_request->isPost() ) {
			if ( ! $this->_request->isXmlHttpRequest() ) {
				 if ( $addForm->isValid( $this->_getAllParams() ) ) {
					$this->doInsert( $addForm->getValues() );
				 }
			} else {
				$data = $addForm->processAjax($_POST);
				if ($data != 'true'){
					 $this->_helper->json( Zend_Json::decode( $data ) );
				} else {
					$this->doInsert( $addForm->getValues() );
					 $this->_helper->json( array( 'success' => true ) );
				}
			}
		}

		$this->view->addForm = $addForm;
    }
	 
	 public function editAction()
	 {
		 $addForm = new Application_Form_Catalog_Add();
		 
		 $id = $this->_getParam('p');
		 if ( $id )
		 {
			 $this->tableCatalog = new Application_Model_Catalog( null );
			 $nodeData = $this->tableCatalog->getNodeById( $id )->toArray();
			 $addForm->populate($nodeData);
			 $addForm->setAction( '/catalog/add/p/'. $nodeData['parent_id']);
		 }
		 
		$this->view->addForm = $addForm;
	 }


	 private function doInsert( $data )
   {
		unset ($data['ajax_callback']);
		$this->tableCatalog = new Application_Model_Catalog( null );
		$this->tableCatalog->insert( $data );
   }

   public function indexAction()
    {
		$this->tableCatalog = new Application_Model_Catalog( null );
		
		$pageId = $this->_getParam('p');
		if ( !$pageId ){
			$this->view->nodeData = $this->tableCatalog->getRoot();
		} else {
			$this->view->nodeData = $this->tableCatalog->getNodeById( $pageId );
		}
	
		$this->view->headTitle('Index Controller');

        //echo $tableCatalog->title.' - '.$tableCatalog->path;
		  //$this->tableCatalog = new Application_Model_Catalog();
        //$this->view->catalogTree = $this->tableCatalog->getPlainTree();
    }

	 public function delAction()
	 {
		$parentId = $this->_getParam('p');
		if ( !$parentId ){
			throw new Exception('No parent node');
		}
		
		$this->tableCatalog = new Application_Model_Catalog( null );
		
		$this->tableCatalog->delete( $parentId );
		
		//echo '<xmp>'.print_r($this->tableCatalog, 1).'</xmp>'; 

		 echo 'Deleted'; exit;
	 }
}